原先Android上是有GridView,以及GridLayout可以用。
但是因為效能問題已經被淡出我們常用的元件類別。
有時候我們還是需要顯示像是圖示等格狀排列,其實現在RecycleView上也可以實現這種樣式。
在RecycleView中,要呈現GridView的樣式,需要用到GridLayoutManager來實作。
一樣先上Activity
class GridViewActivity : AppCompatActivity() {
lateinit var gridLayoutManager: GridLayoutManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
gridLayoutManager = GridLayoutManager(this,2)
recycleview_main.layoutManager= gridLayoutManager //預設
val adapter = RVGridViewAdapter(this, SwitchData.defaultList)
recycleview_main.adapter = adapter
}
}
在設定GridLayoutManager時,需要填入spanCount個數
gridLayoutManager = GridLayoutManager(this,2)
這邊填2表示我們要以每兩個項目作顯示。
Adapter
class RVGridViewAdapter(
private val context: Context,
private val dataList: MutableList<SwitchData>
) :
RecyclerView.Adapter<RVGridViewAdapter.ViewHolder>() {
lateinit var mContext: Context
init {
mContext = context
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
var view = LayoutInflater.from(parent.context).inflate(R.layout.recycleview_gridview_layout, parent, false)
return ViewHolder(view, viewType)
}
override fun getItemCount(): Int {
return dataList.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = dataList[position]
holder?.bindModel(item)
}
inner class ViewHolder(itemView: View, var viewType: Int) : RecyclerView.ViewHolder(itemView) {
var nameTextView: TextView? = null
var likeTextView: TextView? = null
var commentTextView: TextView? = null
fun bindModel(item: SwitchData) {
var imageView: ImageView? = null
imageView = itemView.findViewById(R.id.iv_small)
nameTextView = itemView.findViewById(R.id.tv_namesmall)
Glide.with(mContext).load(item.image).into(imageView!!)
nameTextView?.setText(item.name)
likeTextView?.setText("Likes: ${item.like}")
commentTextView?.setText("comments: ${item.comment}")
}
}
}
透過RecycleView套用GridLayoutManager,我們又能使用這類GridView顯示樣式
同時又能享用RecycleView的資源效能回收的機制。